package com.csun.nusing.ui.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.csun.nusing.R;
import com.csun.nusing.presenter.CommonPresenter;
import com.csun.nusing.ui.BaseActivity;
import com.csun.nusing.ui.adapter.MyBaseAdapter;
import com.csun.nusing.ui.adapter.ViewHolder;
import com.linktop.whealthService.HealthApi;
import com.linktop.whealthService.OnBLEService;

import java.util.ArrayList;
import java.util.List;

/**
 * 搜索蓝牙 ClassName: FollowDeviceSearchActivity
 *
 * @author fzq
 * @Description: TODO
 * @date 2017-11-6
 */
public class FollowDeviceSearchActivity extends BaseActivity<CommonPresenter> {

	private HealthApi mHealthApi;
	public boolean scanning;
	private ListView lv;
	private List<BledeviceInfo> blelist = new ArrayList<BledeviceInfo>();
	private MyBaseAdapter<BledeviceInfo> searchadapter;
	protected TextView rssitv;
	protected TextView nametv;
	protected TextView addresstv;
	private String deviceMacAddress = "";
	private boolean isFamily;
	private RelativeLayout navrl;

	class BledeviceInfo {

		public String address;
		public String name;
		public int rssi;

		public BledeviceInfo(String address, String name, int rssi) {
			super();
			this.address = address;
			this.name = name;
			this.rssi = rssi;
		}
	}

	@Override
	public int getContentViewId() {
		return R.layout.activity_follow_device_search;
	}

	@Override
	public void initSubViews(View view) {
		super.initSubViews(view);
		lv = findViewById(R.id.activity_follow_search_lv);
		navrl = findViewById(R.id.follow_device_search_navrl);
		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				mHealthApi.bleScan(false);
				scanning = false;
				Bundle b = new Bundle();
				b.putString(BluetoothDevice.EXTRA_DEVICE,
						blelist.get(position).address);
				Intent result = new Intent();
				result.putExtras(b);
				setResult(Activity.RESULT_OK, result);
				finish();
			}
		});

	}

	@Override
	public void initData() {
		super.initData();
		deviceMacAddress = getIntent().getStringExtra("deviceMacAddress");
		isFamily = getIntent().getBooleanExtra("isFamily", false);
		if (isFamily) {
			navrl.setBackgroundResource(R.drawable.main_whiteyello_color_shape);
		}
		mHealthApi = new HealthApi();
		mHealthApi.initBleScan(this, mHandler);
		mHealthApi.setBleCallBack(new bleCallBacklistener());
		controlAdapter();
	}

	/**
	 * 绑定适配器
	 * 
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 * @author fzq
	 * @date 2017-11-1
	 */
	private void controlAdapter() {
		searchadapter = new MyBaseAdapter<BledeviceInfo>(this, blelist,
				R.layout.item_follow_blesearch_ll) {
			@Override
			public void convert(ViewHolder helper, int position,
					BledeviceInfo item) {
				rssitv = helper.getView(R.id.item_follow_rssi);
				nametv = helper.getView(R.id.item_follow_name);
				addresstv = helper.getView(R.id.item_follow_address);
				rssitv.setText("" + item.rssi);
				nametv.setText("" + item.name);
				addresstv.setText("" + item.address);
			}
		};
		lv.setAdapter(searchadapter);
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case OnBLEService.GATT_DEVICE_FOUND_MSG:
				Bundle data = msg.getData();
				final BluetoothDevice device = data
						.getParcelable(BluetoothDevice.EXTRA_DEVICE);
				final int rssi = data.getInt(OnBLEService.EXTRA_RSSI);
				Log.e("fzq", "---------address  :  " + device.getAddress());
				Log.e("fzq", "----------deviceMacAddress  :  "
						+ deviceMacAddress);
				if (deviceMacAddress != null && deviceMacAddress.length() > 4) {
					if (device.getAddress().equals(deviceMacAddress)) {
						mHealthApi.bleScan(false);
						scanning = false;
						Bundle b = new Bundle();
						b.putString(BluetoothDevice.EXTRA_DEVICE,
								device.getAddress());
						Intent result = new Intent();
						result.putExtras(b);
						setResult(Activity.RESULT_OK, result);
						finish();
					}
				} else {
					runOnUiThread(new Runnable() {
						private boolean havesamedeviceFlag;
						@Override
						public void run() {
							havesamedeviceFlag = false;
							for (int i = 0; i < blelist.size(); i++) {
								if (blelist.get(i).address.equals(device
										.getAddress())) {
									havesamedeviceFlag = true;
								}
							}
							if (!havesamedeviceFlag) {
								if (device.getName()!=null){
									blelist.add(new BledeviceInfo(device
										.getAddress(), device.getName(), rssi));
									searchadapter.notifyDataSetChanged();
								}
							}
						}
					});
				}
				break;
			default:
				super.handleMessage(msg);
			}
		}
	};

	@Override
	public void onStart() {
		super.onStart();
		IntentFilter filter = new IntentFilter(
				BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
		this.registerReceiver(mReceiver, filter);
	}

	@Override
	public void onStop() {
		super.onStop();
		unregisterReceiver(mReceiver);
	}

	@Override
	protected void onDestroy() {
		mHealthApi.recoverBleScan();
		if (scanning) {
			mHealthApi.bleScan(false);
			scanning = false;
		}
		super.onDestroy();
	}

	/**
	 * The BroadcastReceiver that listens for discovered devices and changes the
	 * title when discovery is finished.
	 */
	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
				setProgressBarIndeterminateVisibility(false);
			}
			if (BluetoothAdapter.ACTION_STATE_CHANGED
					.equals(intent.getAction())) {
			}
		}
	};

	/**
	 * 蓝牙连接监听 ClassName: bleCallBacklistener
	 * 
	 * @Description: TODO
	 * @author fzq
	 * @date 2017-10-25
	 */
	private class bleCallBacklistener implements HealthApi.BleCallBack {
		@Override
		public void bleCallBack(int type, Object data) {
			// TODO Auto-generated method stub
			if (type == HealthApi.BLE_BIND_FINISHED) {
				if (scanning == false) {
					mHealthApi.bleScan(true);
					scanning = true;
				}
			}
		}
	}


}
